/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package sheep.JUNG.utils;


//////////////////////////////////////////////////////////////////////////////////////


import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.util.Iterator;
import java.util.Set;

import javax.swing.AbstractAction;
import javax.swing.JMenu;
import javax.swing.JPopupMenu;


import edu.uci.ics.jung.graph.Edge;
import edu.uci.ics.jung.graph.impl.DirectedSparseEdge;
import edu.uci.ics.jung.visualization.PickSupport;
import edu.uci.ics.jung.visualization.PickedState;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.AbstractPopupGraphMousePlugin;

//////////////////////////////////////////////////////////////////////////////////////
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import sheep.controller.Workspace;
import sheep.model.Project;
import sheep.model.Task;
import sheep.model.graph.OurVertex;
import sheep.view.TransitionManager;


/**
* @author geek
*
*/
public class OurPopupGraphMousePlugin   extends AbstractPopupGraphMousePlugin {

  //////////////////////////////////////////////////////////////////////////////////////

  private Workspace workSpace; 
  private static int i = 0;
  VisualizationViewer vv;
  //////////////////////////////////////////////////////////////////////////////////////

  /**
  * @param preferences
  */
  public OurPopupGraphMousePlugin (Workspace workSpace) {
    this.workSpace = workSpace;
  }

  //////////////////////////////////////////////////////////////////////////////////////


  /* (non-Javadoc)
  * @see edu.uci.ics.jung.visualization.control.AbstractPopupGraphMousePlugin#handlePopup(java.awt.event.MouseEvent)
  */
  protected void handlePopup(MouseEvent e) {
    vv =(VisualizationViewer)e.getSource();
    final Point2D p = e.getPoint();
    final Point2D ivp = vv.inverseViewTransform(e.getPoint());    
    PickSupport pickSupport = vv.getPickSupport();

    if(pickSupport != null) {            
      final OurVertex vertex = (OurVertex)pickSupport.getVertex(ivp.getX(), ivp.getY());
      final DirectedSparseEdge edge = (DirectedSparseEdge)pickSupport.getEdge(ivp.getX(), ivp.getY());
      final PickedState pickedState = vv.getPickedState();
      JPopupMenu popup = new JPopupMenu();

      if(vertex != null) {
        Set<?> picked = pickedState.getPickedVertices();
        
        if(picked.size() > 0) {
          JMenu directedMenu = new JMenu("Creer dependance");
          popup.add(directedMenu);
          
          for(Iterator<?> iterator=picked.iterator(); iterator.hasNext(); ) {
            final OurVertex other = (OurVertex)iterator.next();
            //////////////////////////////////////////////////////////////////////////////////////
            directedMenu.add(new AbstractAction("["+ ((OurVertex)other).getTask().getName()+","+((OurVertex)vertex).getTask().getName()+"]") {
              //////////////////////////////////////////////////////////////////////////////////////
              private static final long serialVersionUID = 1713787010150262446L;
              //////////////////////////////////////////////////////////////////////////////////////

              public void actionPerformed(ActionEvent e) {
                workSpace.getCurrentTask().getGraph().addEdge(other.getTask(), vertex.getTask());
                workSpace.getCurrentProject().getGraph().criticalPath(true);
                vv.repaint();
                TransitionManager.showEdit();
              }
            });
            //////////////////////////////////////////////////////////////////////////////////////
          }
        }
        popup.add(new AbstractAction("Ouvrir sous-graphe"){

          @Override
          public void actionPerformed(ActionEvent e) {
            Task t = workSpace.getCurrentTask().getGraph().getTask(vertex);
            Task current = workSpace.getCurrentTask();
            workSpace.setCurrentTask(t);
            if(t.getGraph() == null)
              t.addGraph(current);
            
            TransitionManager.showProjectGraphEdit();
            vv = workSpace.getCurrentTask().getGraph().getVv();        
          }
          
        });
        //////////////////////////////////////////////////////////////////////////////////////
        popup.add(new AbstractAction("Supprimer tache " + ((OurVertex)vertex).getTask().getName()) {
          //////////////////////////////////////////////////////////////////////////////////////
          private static final long serialVersionUID = -3360950946402258448L;
          //////////////////////////////////////////////////////////////////////////////////////
          public void actionPerformed(ActionEvent e) {
            Task t = workSpace.getCurrentTask().getGraph().getTask(vertex);
            if(!t.equals(workSpace.getCurrentTask().getGraph().getStartTask()) &&
                    !t.equals(workSpace.getCurrentTask().getGraph().getEndTask()))
            {
              pickedState.pick(vertex, false);
              workSpace.getCurrentTask().getGraph().removeVertex(vertex.getTask());
              workSpace.getCurrentProject().getGraph().criticalPath(true);
              vv.repaint();
            }
          }
        });
        //////////////////////////////////////////////////////////////////////////////////////
      }
      else if(edge != null) {
        //////////////////////////////////////////////////////////////////////////////////////
        popup.add(new AbstractAction("Supprimer dependance") {
          //////////////////////////////////////////////////////////////////////////////////////
          private static final long serialVersionUID = -91107971622770354L;
          //////////////////////////////////////////////////////////////////////////////////////
          public void actionPerformed(ActionEvent e) {
            pickedState.pick(edge, false);
            //graph.removeEdge(edge);
            workSpace.getCurrentTask().getGraph().removeEdge(edge);
            vv.repaint();
          }
        });
        //////////////////////////////////////////////////////////////////////////////////////
      }
      else {
        //////////////////////////////////////////////////////////////////////////////////////
        popup.add(new AbstractAction("Creer nouvelleTache") {
          //////////////////////////////////////////////////////////////////////////////////////
          private static final long serialVersionUID = 1064669171364545138L;
          //////////////////////////////////////////////////////////////////////////////////////
          public void actionPerformed(ActionEvent e) {
          Task t = new Task ("New" + i++, workSpace);
          t.addGraph(workSpace.getCurrentTask());
          workSpace.getCurrentTask().getGraph().addVertex(t, p);
          workSpace.getCurrentProject().getGraph().criticalPath(true);
          //workSpace.getCurrentTask().getGraph().writeJPEGImage("C:\\Temp\\jung.png");
          }
        });
        //////////////////////////////////////////////////////////////////////////////////////
        popup.add(new AbstractAction("Créer screenShot") {
          //////////////////////////////////////////////////////////////////////////////////////
          private static final long serialVersionUID = 1064669171364545138L;
          //////////////////////////////////////////////////////////////////////////////////////
          public void actionPerformed(ActionEvent e) {
            //String s1 = "Sheep" ;
            String s =  "Img";
            //boolean mkdir1 = new File(s1).mkdir();
            boolean mkdir = new File(s).mkdir();
            System.out.println("création screenshot : " + s + " : " + mkdir);
              ((Project)workSpace.getCurrentProject()).getGraph().writeJPEGImage(
                      s+ File.separator +((Project)workSpace.getCurrentProject()).getName() +".png", true, vv);
              
              ((Project)workSpace.getCurrentProject()).setPictures(
                      ResizingImage.resize(580, 580,s+ File.separator +((Project)workSpace.getCurrentProject()).getName() +".png"));
              
              ((Project)workSpace.getCurrentProject()).setPicturePath(
                      s+ File.separator +((Project)workSpace.getCurrentProject()).getName() +".png");
          }
        });        
        //////////////////////////////////////////////////////////////////////////////////////
      }
      if(popup.getComponentCount() > 0) 
        popup.show(vv, e.getX(), e.getY());
    }
  }

  
  //////////////////////////////////////////////////////////////////////////////////////
public static class ResizingImage {

  static BufferedImage imgNew = null;


  public static BufferedImage resize(int newWidth, int newHeight, String imgPath) {

  try {
  File imgFile = new File(imgPath);
  BufferedImage imgOld = ImageIO.read(imgFile);
  imgNew = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);

  /// Resizing of the old image ////////////////////////
  Graphics2D g = (Graphics2D) imgNew.getGraphics();
  g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
  g.drawImage(imgOld, 0, 0, newWidth, newHeight, null);
  g.dispose();
  /////////////////////////////////////////////////////

  } catch (IOException e) {
  e.printStackTrace();
  }

  return imgNew;
  }



  public static BufferedImage resize(int newWidth, int newHeight, String imgPath, String strg) {

  imgNew = resize(newWidth, newHeight, imgPath);

  try {
  ImageIO.write(imgNew, "jpeg", new File(strg));
  } catch (IOException e) {
  e.printStackTrace();
  }

  return imgNew;
  }

  } 
}

//////////////////////////////////////////////////////////////////////////////////////
